package auto.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.kipa.utils.PrintUtils;

import java.io.*;
import java.util.Properties;

/**
 * @author qigui.pan
 * @date 2021/5/27
 */

public class PropertiesUtil {


    public String fileName;
    private final Properties properties = new Properties();

    public PropertiesUtil(String fileName) {
        this.fileName = fileName;
        readProperties(fileName);
    }

    /**
     * 读取配置文件
     * @param filePath 配置文件绝对路径
     */
    private void readProperties(String fileName) {
        try {
            InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
            properties.load(in);
        } catch (IOException e) {
            PrintUtils.println(e.toString());
        }
    }


    /**
     * 获取整个配置文件JSONObject格式内容
     * @return JSONObject格式内容
     */
    public JSONObject readProperties() {
        Gson gson = new Gson();
        return JSON.parseObject(gson.toJson(properties));
    }



    /**
     * 根据key读取对应的value
     * @param key 配置文件中对应key
     * @return 若找到key，返回value 否则返回null
     */
    public String getProperty(String key) {
        return properties.getProperty(key);
    }


    /**
     * 设置配置文件中对应的key值
     * @param keyName 配置文件中对应key
     * @param keyValue 对应key的value
     */
    public void setProperties(String keyName, String keyValue) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(this.fileName);
            properties.load(is);
            os = new FileOutputStream(this.fileName);
            properties.setProperty(keyName, keyValue);
            properties.store(os, keyName);
            os.flush();
            os.close();
        } catch (Exception e) {
            PrintUtils.println(e.toString());
        } finally {
            try {
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
                PrintUtils.println(e.toString());
            }
        }
    }
}